import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { ElMessage } from 'element-plus';
import { AxiosInterceptor } from './ApiResponse';

class ApiService {
    private readonly http: AxiosInstance;
    constructor() {
        this.http = axios.create({
            baseURL: 'https://da81-240e-46d-9f00-3537-785b-dd63-3096-d431.ngrok-free.app/backend/api/v1',
            timeout: 5000,
        });
        // 请求拦截器
        this.http.interceptors.request.use((config) => {
            // 在请求发送之前可以做一些处理，例如添加token等
            const token = 'Bearer ' + localStorage.getItem('token'); // 假设token存储在localStorage中
            if (token) {
                config.headers.Authorization = token;
            }
            return config;
        });

        // 响应拦截器
        const responseInterceptor = (response: AxiosResponse<AxiosInterceptor<any>>): Promise<AxiosResponse<AxiosInterceptor<any>>> => {
            // 对响应数据进行处理
            return Promise.resolve(response);
        };
        // 错误处理函数
        const handleErrorResponse = (error: AxiosError): Promise<axios.AxiosResponse> => {
            // 对响应错误进行处理
            let message = '网络出现问题';
            if (error.response) {
                const status = error.response.status;
                switch (status) {
                    case 401:
                        message = 'TOKEN过期';
                        break;
                    case 403:
                        message = '无权访问';
                        break;
                    case 404:
                        message = '请求地址错误';
                        break;
                    case 500:
                        message = '服务器出现问题';
                        break;
                }
            }
            ElMessage({
                type: 'error',
                message: message,
            });
            return Promise.reject(error);
        };

        // 注册拦截器
        this.http.interceptors.response.use(responseInterceptor, handleErrorResponse);

    }

    // 封装GET请求
    get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.http.get(url, config as AxiosRequestConfig<T>);
    }

    // 封装POST请求
    post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.http.post(url, data, config as AxiosRequestConfig<T>);
    }

    // 其他HTTP请求方法的封装...

    // 例如PUT请求
    put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.http.put(url, data, config as AxiosRequestConfig<T>);
    }

    // 例如DELETE请求
    delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.http.delete(url, config as AxiosRequestConfig<T>);
    }
}

const apiService = new ApiService();
export default apiService;
